export async function processStream(stream: ReadableStream): Promise<any[]> {
  if (!stream) return [];
  const reader = stream?.getReader();
  let chunks: any[] = []; // 用于累计文本块

  // read()返回一个Promise，它将解析为一个对象，该对象包含一个{ value, done }结构的字典
  // eslint-disable-next-line no-constant-condition
  while (true) {
    const { value, done } = await reader.read();
    if (done) {
      break; // 流已结束
    }
    const data = new TextDecoder().decode(value);
    const array = data
      .split("\n")
      .filter((line) => line.startsWith("data: "))
      .filter((line) => line !== "data: [DONE]")
      .map((line) => {
        try {
          return JSON.parse(line.substring(6));
        } catch (err) {
          return {};
        }
      });
    chunks = chunks.concat(array);
  }

  return chunks;
}

export function contextToString(data: any[]): string {
  return data
    .map((item: { choices: { delta: { content: string } }[] }) =>
      item?.choices
        ?.map(
          (choice: { delta: { content: string } }) => choice?.delta?.content
        )
        ?.join("")
    )
    ?.join("");
}
